<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      class="frominfo"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <div class="from-item">
        <el-form-item label="任务编号" prop="taskId">
          <el-input
            v-model="queryParams.wcTimedTasks.taskId"
            type="number"
            @keyup.enter.native="handleQuery"
            placeholder="请输入任务编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="创建人" prop="createBy">
          <el-input
            v-model="queryParams.wcTimedTasks.createBy"
            @keyup.enter.native="handleQuery"
            placeholder="请输入创建人"
            clearable
          />
        </el-form-item>
        <el-form-item label="执行时间" prop="executeTime">
          <el-date-picker
            v-model="chatTime"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="chatTimes"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
      </div>
      <div class="from-Btn">
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          style="background-color: #0078fb; color: #fff; border-color: #0078fb"
          icon="el-icon-folder-add"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tuoke:timed:add']"
          >添加任务</el-button
        >
      </el-col>
    </el-row>

    <div class="line-state">
      <div
        class="state-box"
        @click="setState(item.value)"
        :class="
          state == item.value
            ? index == 0
              ? 'select frist-border'
              : index == 2
              ? 'select end-border'
              : 'select'
            : index == 0
            ? 'frist-border'
            : index == 2
            ? 'end-border'
            : ''
        "
        :style="
          index == 1
            ? 'border-right: 1px solid #d1e5ff;border-left: 1px solid #d1e5ff;'
            : ''
        "
        v-for="(item, index) in finishState"
        :key="index"
      >
        {{ item.label }}
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="wcTimedTasksList"
      :header-cell-style="{ background: '#fcfcfd', color: '#000' }"
      :border="false"
    >
      <el-table-column
        label="任务编号"
        prop="taskId"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="创建时间"
        prop="createTime"
        align="center"
        :show-overflow-tooltip="true"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="执行时间"
        prop="executeTime"
        align="center"
        :show-overflow-tooltip="true"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.executeTime, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建人"
        v-if="state == 0"
        prop="createBy"
        align="center"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="执行进度"
        v-if="state != 0"
        prop="finishNum"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope" v-if="state != 0">
          <span
            >{{ scope.row.finishNum }}/{{
              scope.row.executeNum == null ? 0 : scope.row.executeNum
            }}</span
          >
        </template>
      </el-table-column>

      <el-table-column
        label="执行结果"
        v-if="state == 2"
        prop="finishState"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span
            :style="
              scope.row.finishState == 2
                ? 'color:#97c05a'
                : scope.row.finishState == 3
                ? 'color:#c8544b'
                : ''
            "
            >{{
              scope.row.finishState == 2
                ? "任务已完成"
                : scope.row.finishState == 3
                ? "任务已取消"
                : ""
            }}</span
          >
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="warning"
            style="background-color: #fb9d52; color: #fff; width: 50px"
            icon="el-icon-circle-close"
            v-if="state != 2"
            @click="handleUpdate(scope.row)"
            >取消</el-button
          >
          <el-button
            type="warning"
            style="background-color: #fb9d52; color: #fff; width: 50px"
            icon="el-icon-document"
            size="mini"
            @click="golink('/timed/detial', scope.row, 'timedDetial')"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改定时任务信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <div v-if="!end">
        <div class="dia-box">
          <span class="box-txt">请选择营销助手</span>
          <div class="dia-box-search">
            <div class="select-all">
              <i class="el-icon-arrow-right" style="margin-right: 10px"></i
              ><el-checkbox v-model="checkAll" @change="handleCheckAllChange"
                >全选</el-checkbox
              >
            </div>
            <div style="width: 260px">
              <el-input
                placeholder="请输入微信名称"
                v-model="query.wcName"
                class="input-with-select"
              >
<!--                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="search"
                ></el-button>-->
              </el-input>
            </div>
            <div style="width: 10px"></div>
            <div style="width: 260px">
              <el-input
                placeholder="请输入助手名称"
                v-model="query.nickName"
                class="input-with-select"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="search"
                ></el-button>
              </el-input>
            </div>
          </div>
          <span class="box-txt" style="color: red" v-if="show"
            >置灰助手不可选，添加好友超过最高限制</span
          >
          <div class="dia-box-lable" v-if="show">
            <div
              v-for="(item, index) in AssistList"
              :key="index"
              class="lable-box"
              @click="item.canCreateTask ? setIdx(index, item.remark) : goTs()"
              :style="
                item.canCreateTask
                  ? item.remark
                    ? 'background-color: #0078fb;border-color: #0078fb;color: #fff;'
                    : ''
                  : 'background-color: #dcdcdc;'
              "
            >
<!--       原来单展示微信名       {{ item.wcName }}-->
              {{ item.deptName + " -- " + item.nickName}}
            </div>
            <span v-if="AssistList == '' || AssistList == null"
              >暂无助手信息</span
            >
          </div>
          <div class="dia-box-lable">
            <span style="font-size: 14px; color: #9aa5aa">已选：</span>
            <div
              v-for="(item, index) in selectList"
              :key="index"
              class="lable-box"
            >
              {{ item.wcName
              }}<i
                @click="delIdx(index, item.wcId)"
                class="el-icon-close"
                style="margin-left: 10px"
              ></i>
            </div>
            <span v-if="selectList == '' || selectList == null">暂未选择</span>
          </div>
        </div>
        <div
          slot="footer"
          class="dialog-footer"
          style="display: flex; justify-content: center"
        >
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">下一步</el-button>
        </div>
      </div>
      <div
        class="dia-box"
        style="justify-items: center; align-items: center"
        v-else
      >
        <span style="font-size: 14px; margin-right: 10px; line-height: 40px"
          >请选择添加方式</span
        >
        <div
          class="addbtn"
          @click="golink('/friend/add-group', '', 'addGroup')"
        >
          <i class="el-icon-plus"></i><span>群好友添加</span>
        </div>
        <div class="addbtn" @click="golink('/friend/import', '', 'import')">
          <i class="el-icon-plus"></i><span>导入添加</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

  <script>
import request from "@/utils/request";
export default {
  name: "WcGroupsInfo",
  dicts: ["sys_friend_proport"],

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定时任务信息表格数据
      wcTimedTasksList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      chatTime: [],
      chatTimes: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wcTimedTasks: {
          taskId: null, //任务id
          taskType: 0, //任务类型 (0:添加好友任务 1：定时任务  2:群发任务)
          msgType: null,
          executionType: 1, //执行类型不能为空
          executeCycle: null, //执行周期  业务字典（1：每天 2：每周 3：每月 4：每年）
          createBy: null, //创建人
        },
        finishState: 0,
        startExecuteTime: null,
        endExecuteTime: null,
        startCreateTime: null,
        endCreateTime: null,
      },
      show: false,
      query: {
        pageNum: 1,
        pageSize: 999,
        wcId: null,
        deptId: null,
        wcName: null,
        wcNumber: null,
        wcPhone: null,
        nickName: null,
      },
      state: 0,
      finishState: [
        { label: "任务待执行", value: 0 },
        { label: "任务执行中", value: 1 },
        { label: "任务执行结束", value: 2 },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskId: [
          { required: true, message: "任务id不能为空", trigger: "blur" },
        ],
      },
      end: false,
      totals: 0,
      checkAll: false,
      AssistList: [],
      selectList: [],
      addGroupFriend: {
        wcUserInfoList: [],
        wcGroupsUserList: [],
        wcTimedTasks: {
          taskType: 0, //任务类型 (0:添加好友任务 1：定时点赞  2:群发任务)
          executionType: 1, //执行类型不能为空
          executeTime: null, //执行时间
          createTime: null,
          intervalTime: null, //执行间隔时间
          satartDate: null, //开始执行时间//定时执行的时候传该值,该值和executeTime保持一致
        },
        applyContent: null, //申请好友用语
      },
      addType: true,
    };
  },
  mounted() {
    if (this.$store.state.user.roles.includes("common")) {
      this.common = true;
      this.end = true;
      this.addGroupFriend.wcUserInfoList = [{
          wcId: this.$store.state.user.wxid,
          wcName: this.$store.state.user.wcname,
      }];
    }
    this.getList();
  },
  methods: {
    golink(url, type, name) {
      var params = {};
      if (name != "timedDetial") {
        this.addGroupFriend.wcUserInfoList = this.selectList;
        params = this.addGroupFriend;
      } else {
        params = type;
      }
      this.$router
        .push({ path: url, name, query: { info: JSON.stringify(params) } })
        .catch(() => {});
    },
    setState(id) {
      this.state = id;
      this.queryParams.finishState = id;
      this.getList();
    },
    /** 查询定时任务信息列表 */
    getList() {
      this.loading = true;
      listWcTimedTasks(this.queryParams).then((res) => {
        //console.log(res)
        if (res["success"]) {
          const dt = res["data"];
          this.total = dt["total"];
          this.wcTimedTasksList = dt["records"];
        }
        this.loading = false;
      });
      setTimeout(() => {
        this.loading = false;
      }, 2000);
    },
    goTs() {},
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.show = false;
      this.checkAll = false;
      this.AssistList = [];
      this.selectList = [];
      this.addGroupFriend = {
        wcUserInfoList: [],
        wcGroupsUserList: [],
        wcTimedTasks: {
          taskType: 0, //任务类型 (0:添加好友任务 1：定时点赞  2:群发任务)
          executionType: 1, //执行类型不能为空
          createTime: null,
          executeTime: null, //执行时间
          intervalTime: null, //执行间隔时间
          satartDate: null, //开始执行时间//定时执行的时候传该值,该值和executeTime保持一致
        },
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.startExecuteTime = null;
      this.queryParams.endExecuteTime = null;
      if (this.chatTime != "" && this.chatTime != null) {
        this.queryParams.startExecuteTime = this.chatTime[0] + " 00:00:00";
        this.queryParams.endExecuteTime = this.chatTime[1] + " 23:59:59";
      }

      this.queryParams.startCreateTime = null;
      this.queryParams.endCreateTime = null;
      if (this.chatTimes != "" && this.chatTimes != null) {
        this.queryParams.startCreateTime = this.chatTimes[0] + " 00:00:00";
        this.queryParams.endCreateTime = this.chatTimes[1] + " 23:59:59";
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.chatTime = [];
      this.chatTimes = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        wcTimedTasks: {
          taskId: null, //任务id
          taskType: 0, //任务类型 (0:添加好友任务 1：定时任务  2:群发任务)
          msgType: null,
          executionType: 1, //执行类型不能为空
          executeCycle: null, //执行周期  业务字典（1：每天 2：每周 3：每月 4：每年）
          createBy: null, //创建人
        },
        finishState: this.state,
        startExecuteTime: null,
        endExecuteTime: null,
        startCreateTime: null,
        endCreateTime: null,
      };
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getAssist().then((res) => {
        if (this.addType) {
          this.open = true;
          this.title = "新增任务";
        } else {
          this.$message({
            message: "添加好友已经超过最高限制！",
            type: "warning",
          });
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$modal
        .confirm("是否确认取消所选定时任务信息？")
        .then(function () {
          return updateWcTimedTasks(row.id);
        })
        .then(() => {
          this.getList();
          this.open = false;
          this.$modal.msgSuccess("取消成功");
        })
        .catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      if (this.selectList != null && this.selectList != "") {
        this.end = true;
      } else {
        this.$message({
          message: "请先选择助手！",
          type: "warning",
        });
      }
    },
    search() {
      this.show = true;
      this.getAssist()
    },
    async getAssist() {
      await listWcAssist(this.query).then((res) => {
        if (res["success"]) {
          const dt = res["data"];
          this.totals = dt["total"];
          dt["records"].forEach((element) => {
            element.remark = false;
          });
          this.AssistList = dt["records"];
          if (this.$store.state.user.roles.includes("common")) {
            this.addType = dt["records"][0].canCreateTask;
          }
        }
      });
    },
    handleCheckAllChange(selection) {
      if (this.AssistList != null && this.AssistList != "") {
        this.checkAll = selection;
        if (selection) {
          // "wcNumber": item.wcNumber,"wcImg": item.wcImg, "wcPhone": item.wcPhone,"region": item.region, "loginTime": item.loginTime,"loginState": 1, "olState": 1
          this.selectList = this.AssistList.map((item) => {
            const newItem = { wcId: item.wcId, wcName: item.wcName };
            return newItem;
          });
          this.AssistList.forEach((element) => {
            element.remark = true;
          });
        } else {
          this.selectList = [];
          this.AssistList.forEach((element) => {
            element.remark = false;
          });
        }
      } else {
        this.checkAll = false;
        this.$message({
          message: "请先搜索助手！",
          type: "warning",
        });
      }
    },
    setIdx(idx, type) {
      if (!type) {
        this.AssistList[idx].remark = true;
        var item = this.AssistList[idx];
        this.selectList.push({
          //assistId: item.assistId,
          wcId: item.wcId,
          wcName: item.wcName,
          //wcNumber: item.wcNumber,
          //wcImg: item.wcImg,
          //wcPhone: item.wcPhone,
          //region: item.region,
          //loginTime: item.loginTime,
          //loginState: 1,
          //olState: 1,
          //remark: "",
        });
      }
    },
    delIdx(idx, id) {
      this.checkAll = false;
      this.selectList.splice(idx, 1);
      this.AssistList.forEach((element) => {
        if (element.wcId == id) {
          element.remark = false;
        }
      });
    },
  },
};

/** js请求 调用 */

// 查询定时任务信息列表
export function listWcTimedTasks(query) {
  return request({
    url: "/arbit/wctimedTasks/getPage",
    method: "post",
    data: query,
  });
}
// 查询助手信息列表
export function listWcAssist(query) {
  return request({
    url: "/arbit/wcuser_info/page",
    method: "get",
    params: query,
  });
}
// 修改定时任务信息
export function updateWcTimedTasks(id) {
  return request({
    url: "/arbit/wctimedTasks/cancelTask/" + id,
    method: "POST",
  });
}
</script>
  <style scoped lang="scss">
.app-container {
  background-color: #f6f9fb;
}
.line-state {
  display: flex;
  width: 390px;
  border: 1px solid #d1e5ff;
  font-size: 14px;
  border-radius: 5px;
  background-color: #fff;
  .state-box {
    width: 130px;
    height: 35px;
    color: #8c8c8c;
    text-align: center;
    line-height: 35px;
  }
  .frist-border {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
  }
  .end-border {
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
  }
  .select {
    color: #fff;
    background-color: #288dfc;
  }
}
.frominfo {
  display: flex;
  background-color: #fff;
  padding: 10px;
  padding-bottom: 0;
  margin-bottom: 20px;
  .from-item {
    display: flex;
    flex-wrap: wrap;
  }
  .from-Btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 20%;
  }
}
.linebtn {
  display: flex;
  margin: -10px 0 10px 5px;
  height: 38px;
  .btn {
    width: 180px;
    text-align: center;
    line-height: 38px;
    font-size: 14px;
    color: #8c8c8c;
    margin-right: 10px;
    border: 1px solid #eaeff2;
    background-color: #fff;
    border-radius: 5px;
    .link-type {
      color: #8c8c8c;
    }
  }
  .select {
    background-color: #eaf6ff;
    border: 1px solid #288dfc;
    color: #288dfc;
    font-weight: 550;
  }
}
.dia-box {
  margin-top: -20px;
  padding: 0 20px 20px 20px;
  display: flex;
  flex-direction: column;
  .box-txt {
    font-size: 14px;
    margin-right: 10px;
    line-height: 40px;
  }
  .dia-box-search {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .select-all {
      border: 1px solid #dcdfe6;
      height: 36px;
      line-height: 36px;
      padding: 0 10px;
      border-radius: 4px;
    }
  }
  .dia-box-time {
    display: flex;
    flex-direction: column;
  }
  .dia-box-lable {
    width: 90%;
    border-radius: 5px;
    border: 1px solid #eee;
    min-height: 100px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    margin-bottom: 20px;
    .lable-box {
      padding: 0 5px;
      margin: 3px 0;
      height: 20px;
      line-height: 18px;
      margin-right: 10px;
      border: 1px solid #dcdcdc;
      background-color: #ebf4ff;
      font-size: 12px;
      border-radius: 3px;
    }
    .select {
      color: #fff;
      background-color: #4095e5;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: center;
  }
  .addbtn {
    width: 130px;
    border-radius: 5px;
    background-color: #0078fb;
    border-color: #0078fb;
    font-size: 15px;
    text-align: center;
    height: 40px;
    line-height: 40px;
    color: #fff;
    margin-bottom: 15px;
    cursor: pointer;
  }
}
</style>
